<template>
	<SkeletonScreen v-if="loading"></SkeletonScreen>
	<view class="container">
		<!-- 顶部导航 -->
		<custom-nav-tabs :tabs="['筛选', '推荐']" default-index="1" :defaultIndex="activeTab" @change="onTabChange">
			<!-- 可自定义左侧图标 -->
			<template #left>
				<view class="nav-left">
					<view style="padding-right: 40rpx;" @click="onperson('/pages/of_play/Watch/Watch')">
						<uni-icons type="person" size="28" color="#ff0000" />
					</view>
					<view @tap="onperson('/pages/of_play/search/search')">
						<uni-icons type="search" size="28" color="#ff0000" />
					</view>
				</view>
			</template>
			<!-- 可自定义右侧内容 -->
			<template #right>
				<view style="width: 60rpx;"></view>
			</template>
		</custom-nav-tabs>

		<!-- 页面内容 -->
		<view class="video-swiper" v-if="activeTab === 0">
			<view style="width: 100%; height: 180rpx;"></view>
			
			
			<view style="position: fixed;top: 160rpx; z-index: 100; width: 100%;height: 70rpx; background-color: #000000;" >
				<my-scroll-navbar @TagIndex="onnavIndex" :list="navIndexValue" :isNav="false"
					:isIcon="false"></my-scroll-navbar>
			</view>
			
			<scroll-view style="margin-top: 70rpx;" @scrolltolower="onBottumLoadingA" class="swiper-topic-list" scroll-y="true">
				<view class="img-three">
					<view class="image-eight-Three">
						<my-img-y-Three class="item" v-for="item in ImgPlayValue" :images="item.imageUrl"
							:name="item.name" :biao="item.tagsName" :episode="item.episode" :episodes="item.episode"
							:urlId="item.id" :urlName="'/pages/of_play/play/play?'"></my-img-y-Three>
					</view>
				</view>

				<view
					style="display: flex; justify-content: center; align-items: center; padding: 30rpx 0; color: #464646;">
					<view>到此为止...</view>
				</view>
			</scroll-view>

		</view>
		<view class="video-swiper" v-if="activeTab === 1">
			<!-- 全屏 Swiper 容器 @change="onSwiperChange"-->
			<swiper class="video-swiper" :current="currentIndex" @change="onSwiperChangeThrottled" vertical
				:duration="150">
				<!-- 控制只渲染当前索引前后3个视频，防止内存溢出 -->
				<swiper-item v-for="(item,index) in videos" :key="item.id" class="swiper-item">
					<view class="video-wrapper" @tap="togglePlay(item.id)" v-if="isVideoVisible(index)">
						<!-- 视频播放器 -->
						<video :id="'MyPlayer' + item.id" :src="item.videoUrl" :show-mute-btn="true" v-if="videoNav"
							:show-play-btn="true" :show-fullscreen-btn="false" auto-pause-if-navigate
							:auto-pause-if-navigate="true" :auto-pause-if-open-native="true" auto-pause-if-open-native
							controls class="fullscreen-video" @play="onPlay(item.id)" @pause="onPause(item.id)"
							@ended="onEnded(item.id)" @error="onVideoError" @waiting="onwaiting">
						</video>

						<!-- 短剧相关的信息 -->
						<view class="video-c-title">
							<view class="v-title">{{item.collectionPlays[0].name}}</view>
							<view class="v-tags">
								<view>{{item.collectionPlays[0].tagsName}}</view>
								<view>｜</view>
								<view>第{{item.videoJi}}集</view>
							</view>
							<!-- :url="`/pages/of_play/play/play?id=${item.collectionPlays[0].id}`" -->
							<view  class="c-icon-title" @click.stop="forwardFunction(item.collectionPlays[0].id)">
								<view class="c-icon-">
									<view>
										<uni-icons color="#fff" type="fire" size="25"></uni-icons>
									</view>
									<view>观看完整短剧·</view>
									<view>全{{item.collectionPlays[0].episode}}集</view>
								</view>
								<view>
									<uni-icons color="#fff" type="forward" size="24"></uni-icons>
								</view>
							</view>
							
						</view>
						<!-- 自定义播放/暂停图标 -->
						<!-- <view class="play-pause-icon" v-if="playingId !== item.id">
							<image src="/static/icon/of-s.png" />
						</view> -->
						<!-- 转发，评论 -->
						<SocialActions :videoContent="currentIndex ? videos[currentIndex] : videos[0]" />
					</view>
				</swiper-item>
			</swiper>
		</view>

	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		nextTick
	} from 'vue'

	import {
		newVideosList,
		newVideosUrl,
		newTagsIndex,
		collectionPlay,
		updadeVideosCreate
	} from '@/API/ofPlayApis.js';
	import {
		onShow
	} from '@dcloudio/uni-app';
	onShow(() => {
	videoNav.value = true;
	
	})

	import CustomNavTabs from '@/components/ofPlay/CustomNavTabs.vue'
	import SocialActions from '@/components/ofPlay/SocialActions.vue';
	import {
		onReachBottom
	} from '@dcloudio/uni-app';
	const loading = ref(true)
	// 先获取用户信息然后进行存储
	// #ifdef MP-WEIXIN
	const user = ref(uni.getStorageSync("user"));
	// #endif

	const activeTab = ref(1) //导航栏
	const ImgPlayValue = ref([]);
	// 导航栏调换函数
	const onTabChange = (index) => {
		activeTab.value = index
		if (activeTab.value == 0) {
			onNavIndexFunction();
			collectionPlayFunction(PlayPageNum.value, onaNavTagsIndex.value);
			loading.value = true
		}

	}

	// 数据分页配置
	const pageNum = ref(1) //短剧下一页
	const PlayPageNum = ref(1) //筛选下一页
	const onaNavTagsIndex = ref(0);
	const loadingMore = ref(false)
	const navIndexValue = ref([]);
	const episodeCountValue = ref(1);

	// 当前播放索引
	const currentIndex = ref(0)
	const playingId = ref(null)
	const isPlaying = ref(false)
	const playIcon = ''
	const pauseIcon = '/static/icon/of-s.png'

	// 视频数据（分页加载）
	const videos = ref([]);

	// 视频上下文对象
	const videoContexts = ref({});

	// 获取筛选导航栏数据
	const onNavIndexFunction = async () => {
		let res = await newTagsIndex();
		console.log("tags:", res);
		navIndexValue.value = res;

	}

	// 获取筛选短剧信息
	const collectionPlayFunction = async (pageNum, tags) => {
		let res = await collectionPlay(pageNum, 16, tags);
		console.log("video数据:", res);
		// 创建一个 Set 来记录已存在的 id
		const existingIds = new Set(ImgPlayValue.value.map(item => item.id));
		// 过滤 res.list，只添加 id 不存在于 existingIds 中的项
		const newItems = res.list.filter(item => !existingIds.has(item.id));
		// 合并更新
		ImgPlayValue.value = ImgPlayValue.value.concat(newItems);
		PlayPageNum.value = res.nextPage;
		loading.value = false
	}

	// 方法：判断当前视频是否可见（前后3个）
	const isVideoVisible = (index) => {
			
		const diff = Math.abs(index - currentIndex.value)
		
		return diff <= 3 // 前后 3 个都渲染
	}


	// 定义节流函数，用于限制函数调用频率
	const throttle = (fn, delay) => {
		let lastTime = 0
		return function(...args) {
			const now = Date.now()
			if (now - lastTime >= delay) {
				fn.apply(this, args)
				lastTime = now
			}
		}
	}

	// 定义防抖函数，用于减少不必要的函数调用
	const debounce = (fn, delay) => {
		let timer = null
		return function(...args) {
			if (timer) clearTimeout(timer)
			timer = setTimeout(() => {
				fn.apply(this, args)
			}, delay)
		}
	}

	// 优化后的视频上下文创建函数，添加防抖处理
	const createVideoContextDebounced = debounce((id) => {
		if (!videoContexts.value[id]) {
			videoContexts.value[id] = uni.createVideoContext('MyPlayer' + id)
		}
	}, 300)

	// 优化 onSwiperChange 函数，添加节流处理
	const onSwiperChangeThrottled = throttle((e) => {
		const newIndex = e.detail.current
		const oldId = videos.value[currentIndex.value]?.id
		const wchatVideo = videos.value[currentIndex.value];

		pauseOtherVideos(oldId)

		// 暂停旧视频
		if (oldId && videoContexts.value[oldId]) {
			videoContexts.value[oldId].pause()
			updateCreateFunction(user.value.id, oldId, wchatVideo.videoId, wchatVideo.videoJi)
		}

		currentIndex.value = newIndex

		// 获取当前视频 ID
		const newId = videos.value[newIndex]?.id

		// 创建当前视频上下文（如果不存在）
		if (newId) {
			createVideoContextDebounced(newId)
		}
		episodeCountValue.value = videos.value[newIndex]?.videoJi;

		// 预加载前后 2 个视频的上下文
		const preloadRange = 3
		const start = Math.max(0, newIndex - preloadRange)
		const end = Math.min(videos.value.length - 1, newIndex + preloadRange)

		for (let i = start; i <= end; i++) {
			const id = videos.value[i]?.id
			if (id) {
				createVideoContextDebounced(id)
			}
		}

		// 自动播放
		if (newId) {
			play(newId)
		}

		// 清理超出范围的视频和上下文
		cleanUpOldVideos(newIndex)
		if (newIndex === videos.value.length - 1) {
			loadMoreData(pageNum.value)
		}
	}, 300)

	// 观看记录
	const updateCreateFunction = async (userId, urlId, videoId, episodesCount) => {
		let res = await updadeVideosCreate(userId, urlId, videoId, episodesCount);
		// console.log("观看记录已更新")
	}

	// 方法：播放视频
	const play = (id) => {
		console.log("准备播放视频 ID:", id)

		let retry = 0
		const maxRetry = 5

		const tryPlay = () => {
			if (!videoContexts.value[id]) {
				console.log("未找到上下文，尝试创建：", id)
				videoContexts.value[id] = uni.createVideoContext('MyPlayer' + id)
			}

			const context = videoContexts.value[id]
			if (context) {
				playingId.value = id
				isPlaying.value = true

				setTimeout(() => {
					context.play()
					console.log("调用 play 成功")
				}, 50)
			} else if (retry < maxRetry) {
				console.log("上下文未准备好，重试第", retry + 1, "次")
				retry++
				setTimeout(tryPlay, 100)
			} else {
				console.error("重试失败，无法播放视频 ID:", id)
			}
		}

		tryPlay()
	}

	// 方法：暂停视频
	const pause = (id) => {
		const context = videoContexts.value[id]
		if (context) {
			context.pause()
		}
		isPlaying.value = false
	}

	// 方法：切换播放/暂停
	const togglePlay = (id) => {
		if (playingId.value === id) {
			pause(id)
			playingId.value = null
			isPlaying.value = false
		} else {
			if (playingId.value && videoContexts.value[playingId.value]) {
				videoContexts.value[playingId.value].pause()
				isPlaying.value = false
			}
			play(id)
			isPlaying.value = true
		}
	}

	const isVideoLoading = ref(false);
	const onwaiting = () => {
		// uni.showLoading({
		// 	title: '加载中...'
		// })
		// isVideoLoading.value = true;

		// // 3秒后强制隐藏提示（防止未触发onPause）
		// setTimeout(() => {
		// 	if (isVideoLoading.value) {
		// 		uni.hideLoading();
		// 		isVideoLoading.value = false;
		// 	}
		// }, 2000)
	}


	// 方法：视频播放开始
	const onPlay = (id) => {
		if (isVideoLoading.value) {
			uni.hideLoading();
			isVideoLoading.value = false;
		}
		playingId.value = id
		isPlaying.value = true
	}

	// 方法：视频暂停
	const onPause = (id) => {
		uni.hideLoading()
		if (playingId.value === id) {
			playingId.value = null
			isPlaying.value = false
		}
	}

	// 方法：视频播放结束，自动播放下一个
	const onEnded = (id) => {
		const index = videos.value.findIndex(v => v.id === id)
		if (index < videos.value.length - 1) {
			currentIndex.value = index + 1
			setTimeout(() => {
				play(videos.value[currentIndex.value].id)
			}, 100)
		} else {
			loadMoreData(pageNum.value)
		}
	}

	const MAX_VIDEO_CACHE = 22;
	const playHistory = []; // 播放记录，用于 LRU 缓存策略

	const loadMoreData = async (page) => {
		// uni.showLoading({
		// 	title: '加载中...'
		// });
		if (page == 0) {
			uni.showToast({
				title: '没有更多内容了'
			});
			return;
		}

		try {
			// #ifdef MP-WEIXIN
			let user = uni.getStorageSync("user");
			let userId = user.id;
			console.log("用户信息:", user);
			console.log("userId:", userId);
			// #endif
			const res = await newVideosUrl(page, userId);
			if (res) {
				uni.hideLoading();
			}
			console.log("数据：", res.list);

			const newVideos = res.list;
			pageNum.value = res.nextPage;
			// 使用 Map 合并新旧数据，id 相同则合并（新数据覆盖旧数据）
			const videoMap = new Map();

			videos.value.forEach(video => {
				videoMap.set(video.id, video);
			});

			newVideos.forEach(video => {
				videoMap.set(video.id, video);
			});

			videos.value = Array.from(videoMap.values());

			// 用于缓存管理的视频 id 列表（排除当前播放的）
			const currentVideoId = videos.value[currentIndex.value]?.id;
			const cacheableVideos = videos.value.filter(v => v.id !== currentVideoId);

			// 优先释放未播放过的视频上下文
			while (Object.keys(videoContexts.value).length >= MAX_VIDEO_CACHE) {
				let idToRemove = null;

				// 找一个不在播放记录中的视频
				for (let i = 0; i < cacheableVideos.length; i++) {
					if (!playHistory.includes(cacheableVideos[i].id)) {
						idToRemove = cacheableVideos[i].id;
						break;
					}
				}

				// 如果没找到，就找最早播放的
				if (!idToRemove && playHistory.length > 0) {
					idToRemove = playHistory[0];
				}

				// 如果都没找到，随便选一个
				if (!idToRemove) {
					idToRemove = Object.keys(videoContexts.value).find(id => id !== currentVideoId) || null;
				}

				if (idToRemove && videoContexts.value[idToRemove]) {
					videoContexts.value[idToRemove].pause();
					videoContexts.value[idToRemove] = null;
					delete videoContexts.value[idToRemove];
					console.log("已释放视频上下文：", idToRemove);
				} else {
					break;
				}
			}

			// 更新播放历史
			if (currentVideoId && !playHistory.includes(currentVideoId)) {
				playHistory.push(currentVideoId);
				if (playHistory.length > 15) {
					playHistory.shift();
				}
			}

			await nextTick();

			// ✅ 创建新视频的上下文
			newVideos.forEach((item) => {
				if (!videoContexts.value[item.id]) {
					videoContexts.value[item.id] = uni.createVideoContext('MyPlayer' + item.id);
				}
			});

			// ✅ 主动为第一个视频创建上下文（即使它不是新视频）
			const firstVideo = videos.value[0];
			if (firstVideo && !videoContexts.value[firstVideo.id]) {
				videoContexts.value[firstVideo.id] = uni.createVideoContext('MyPlayer' + firstVideo.id);
			}

			console.log("当前缓存上下文 id 列表：", Object.keys(videoContexts.value));
			loading.value = false
		} catch (error) {
			console.error('加载数据失败:', error);
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			});
		} finally {
			loadingMore.value = false;
		}
	};
	// 清理不适用的上下文
	const cleanUpOldVideos = (currentIndex) => {
		const visibleRange = {
			start: Math.max(0, currentIndex - 3),
			end: Math.min(videos.value.length - 1, currentIndex + 3)
		}

		// 保留上下文缓存，只清理超出范围的
		Object.keys(videoContexts.value).forEach(id => {
			const index = videos.value.findIndex(v => v.id === parseInt(id))
			if (index !== -1 && (index < visibleRange.start || index > visibleRange.end)) {
				// 暂停并清理上下文
				videoContexts.value[id].pause()
				delete videoContexts.value[id]
			}
		})
	}
	// 播放异常
	const onVideoError = (e) => {
		uni.showToast({
			title: '视频加载失败',
			icon: 'none'
		})
	}

	function pauseOtherVideos(currentId) {
		Object.keys(videoContexts.value).forEach(id => {
			if (id !== currentId && videoContexts.value[id]) {
				videoContexts.value[id].pause();
			}
		});
	}
	// 筛选导航栏
	function onnavIndex(e) {
		console.log(e.item.sortId);
		onaNavTagsIndex.value = e.item.sortId;
		ImgPlayValue.value = [];
		PlayPageNum.value = 1;
		collectionPlayFunction(1, e.item.sortId);
	}
	// 图标导航栏
	function onperson(url) {
		console.log(url);
		uni.navigateTo({
			url: url
		})
	}
	const videoNav = ref(true)
	// 随机短剧信息递给播放页面
	function forwardFunction(e) {
		videoNav.value = false;
		uni.navigateTo({
		  url: `/pages/of_play/play/play?id=${encodeURIComponent(e)}`
		})
	}
	// 推荐页面触底函数
	function onBottumLoadingA() {
		console.log("PlayPageNum.value", PlayPageNum.value);
		if (PlayPageNum.value > 1) {
			collectionPlayFunction(PlayPageNum.value, onaNavTagsIndex.value);
			console.log("触底了scroll")
		}
	}
	// 生命周期
	onMounted(() => {
		console.log("开始加载第一页数据")
		loadMoreData(pageNum.value)

		if (videos.value.length > 0) {
			play(videos.value[0]?.id)
		}

	})
</script>

<style scoped>
	.container {
		width: 100%;
		height: 100vh;
		overflow: hidden;
		background-color: black;
	}

	.navBottum {
		/* 顶部导航占位 */
	}

	.video-swiper {
		width: 100%;
		height: 100%;
	}

	.swiper-item {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.video-wrapper {
		width: 100%;
		height: 100%;
		position: relative;
	}

	.fullscreen-video {
		width: 100%;
		height: 100%;
		background-color: black;
	}

	.play-pause-icon {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 60px;
		height: 60px;
		z-index: 100;
		opacity: 0.7;
	}

	.play-pause-icon image {
		width: 100%;
		height: 100%;
	}

	.loading {
		text-align: center;
		padding: 10px;
		color: white;
	}

	.video-c-title {
		pointer-events: auto;
		width: 100%;
		position: fixed;
		bottom: 70rpx;
		z-index: 10;

	}

	.v-title {
		font-size: 28rpx;
		font-weight: bold;
		padding: 0 30rpx;
	}

	.v-tags {
		display: flex;
		align-items: center;
		font-size: 22rpx;
		padding: 10rpx 30rpx;
	}

	.c-icon-title {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: rgba(0, 0, 0, 0.3);
		padding: 10rpx 20rpx;
		font-size: 24rpx;
		box-sizing: border-box;

	}

	.c-icon- {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.image-eight-Three {
		width: 100%;
		position: relative;
		margin: 0 auto;
		box-sizing: border-box;
		padding: 20rpx 30rpx;
		display: grid;
		gap: 15rpx;
		grid-template-columns: repeat(3, 1fr);
		border-radius: 20rpx;
	}

	.item {
		overflow: hidden;
		/* 防止内容溢出 */
		position: relative;
		width: 100%;
		/* 图片宽度填充整个容器 */
		height: auto;
		/* 根据宽度自动调整高度 */
		display: block;
		/* 移除图片下方默认的空白间隙 */
		object-fit: cover;
		/* 保证图片完全覆盖容器，可能会裁剪图片 */
	}

	.nav-left {
		width: 140rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;

	}

	.swiper-topic-list {
		width: 100%;
		height: 90vh;
		
	}
</style>